package com.weme.common.activity

import android.app.ActivityOptions
import android.content.Intent
import android.os.Bundle
import android.text.TextUtils
import android.util.Log
import android.widget.ImageView
import androidx.activity.OnBackPressedCallback
import androidx.fragment.app.FragmentActivity
import com.osom.proto.message.Brocast
import com.weme.common.R
import com.weme.common.base.BaseMvvmActivity
import com.weme.common.databinding.ActivityCallBinding
import com.weme.common.ext.*
import com.weme.common.network.*
import com.weme.common.util.*
import com.weme.common.viewmodel.CallViewMode
import dev.kratos.api.im_server.v1.*
import kotlinx.coroutines.*

enum class CallOperationType {
    INCOMING_VIDEO, OUTGOING_VIDEO
}

class CallActivity : BaseMvvmActivity<ActivityCallBinding, CallViewMode>() {
     var videoCallMessage: Brocast.VideoCallMessage? = null
     var callVideoReply: CallsPhone? = null
     lateinit var callOperationType: CallOperationType
     val delayMillis: Long = 60000 // 60秒

     var callType = -1
     var channelName = ""
     var countdownJob: Job? = null
     var countdownLongJob: Job? = null

     val runnable = Runnable {
        countdownLongJob?.cancel()
        handleCallType()
    }

    companion object {
        private const val EXTRA_CALL_OPERATION_TYPE = "CallOperationType"
        private const val EXTRA_BEAN = "BEAN"

        fun openActivity(activity: FragmentActivity, callType: CallOperationType, bean: Any? = null) {
            val intent = Intent(activity, CallActivity::class.java)
            val options = ActivityOptions.makeCustomAnimation(activity, R.anim.fade_in, R.anim.fade_out)
            intent.putExtra(EXTRA_CALL_OPERATION_TYPE, callType.toString())
            intent.putExtra(EXTRA_BEAN, bean as? java.io.Serializable)
            activity.startActivity(intent, options.toBundle())
        }
    }

    override fun getViewModelClass(): Class<CallViewMode> = CallViewMode::class.java

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        overridePendingTransition(R.anim.fade_in, R.anim.fade_out)
    }

    override fun initView(savedInstanceState: Bundle?) {
        callOperationType = intent.getStringExtra(EXTRA_CALL_OPERATION_TYPE)?.let { CallOperationType.valueOf(it) } ?: return
        when (callOperationType) {
            CallOperationType.OUTGOING_VIDEO -> setupOutgoingCall()
            CallOperationType.INCOMING_VIDEO -> setupIncomingCall()
        }
        mBinding.imAccept.playSVGAFromAssets("video_button_male_call_message")
        setupCommonViews()
        setupOnClickListeners()
    }

    private fun setupOutgoingCall() {
        getViewBind().groupAccept.gone()
        callVideoReply = intent.getSerializableExtra(EXTRA_BEAN) as CallsPhone
        callVideoReply?.apply {
            initUserInfoView(user)
            getViewMode().callVideo(this.user.uid)
        }
    }

    private fun setupIncomingCall() {
        videoCallMessage = intent.getSerializableExtra(EXTRA_BEAN) as Brocast.VideoCallMessage
        videoCallMessage?.apply {
            val userInfo = getString(com.example.resources.R.string.user_info_format, this.caller.nickname, this.caller.age)
            mBinding.tvName.text = userInfo
            if (!TextUtils.isEmpty(caller.video)) {
                playVideo(caller.video)
            } else {
                setupDefaultIncomingCallView()
            }
        }
    }

    private fun setupDefaultIncomingCallView() {
        val imageView = ImageView(this@CallActivity).apply {
            scaleType = ImageView.ScaleType.CENTER_CROP
        }
        getViewBind().localVideoViewContainer.addView(imageView)
        imageView.loadImageWithPlaceholderAndTransformation(videoCallMessage?.caller?.cover, 5, 2)
        val country = getCountryBean(videoCallMessage?.caller?.countryCode)
        country?.let {
            mBinding.imCountry.loadImage(it.countryFlag)
            mBinding.tvLanguage.text = it.countryName
        }
    }

    private fun setupCommonViews() {
        isSubscribeInfo()
        setModeView()
    }

    override fun onResume() {
        super.onResume()
        if (callOperationType != CallOperationType.OUTGOING_VIDEO) {
            viewModel.getChannelInfo()
        }
        onBackPressedDispatcher.addCallback(this, onBackPressedCallback)
    }

    override fun onDestroy() {
        cleanupResources()
        super.onDestroy()
        mBinding.imAccept.stopAnimation()
        mBinding.imAccept.clear()
    }

    private fun cleanupResources() {
        stopPlay()
        countdownJob?.cancel()
        countdownLongJob?.cancel()
        mBinding.countdownProgressBar.stopCountDown()
    }

     val onBackPressedCallback = object : OnBackPressedCallback(true) {
        override fun handleOnBackPressed() {
            mBinding.countdownProgressBar.stopCountDown()
            finish()
            overridePendingTransition(R.anim.fade_in, R.anim.fade_out)
        }
    }
    fun getViewMode(): CallViewMode {
        return viewModel
    }

    fun getViewBind(): ActivityCallBinding {
        return mBinding
    }

    override fun onBackPressed() {
        if (callOperationType == CallOperationType.OUTGOING_VIDEO) {
            callVideoReply?.apply {
                viewModel.setHangUp(this.user.uid)
            }
        } else {
            viewModel.setHangUp(videoCallMessage!!.caller.uid, videoCallMessage!!.channelName)
        }
    }

    private fun handleCallType() {
        when (callType) {
            0 -> {
                finish()
                showToast(resources.getString(com.example.resources.R.string.call_now))
                AgoraClient.getInstance().sendImCallMsg(callVideoReply!!.user.uid.toString())
            }
            1 -> showToast("跳转到订阅商城").also { finish() }
            2, 3 -> showToast("跳转到金币商城").also { finish() }
        }
    }
}
